package model

import (
	"github.com/yeahyf/go_base/cfg"
	"github.com/yeahyf/go_base/log"
	"github.com/yeahyf/go_base/rds"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
)

var (
	PictureDB *gorm.DB
)

// Init 初始化数据库
func Init() {
	// 实现读写分离的配置
	maxOpenConn := cfg.GetInt("tutu.mysql.open.size") //最大连接数
	connMaxLife := cfg.GetInt("tutu.mysql.life.time") //连接最大生命周期
	maxIdleConn := cfg.GetInt("tutu.mysql.idle.size") //最大空闲连接数
	maxIdleTime := cfg.GetInt("tutu.mysql.idle.time") //连接最大空闲时间
	addr := cfg.GetString("tutu.mysql.address")       //地址
	client := rds.NewSQLClient(addr,
		rds.WithMaxOpenConn(maxOpenConn),
		rds.WithConnMaxLifetime(connMaxLife),
		rds.WithMaxIdleConn(maxIdleConn),
		rds.WithConnMaxIdleTime(maxIdleTime))

	db, err := gorm.Open(mysql.New(mysql.Config{Conn: client}), &gorm.Config{})
	if err != nil {
		log.Error(err)
		os.Exit(0)
	}
	PictureDB = db

	err = PictureDB.AutoMigrate(&SysUser{})
	if err != nil {
		log.Error(err)
		return
	}
}
